package com.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.entity.AsCustoms;
import com.entity.AsKeywords;
import com.entity.AsUser;
import com.entity.MethodLog;
import com.service.*;
import com.utils.AnnotationUtil;
import com.utils.JsonUtil;
import com.utils.Pager;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Controller
public class AgentManageController
{
    @Resource
    private AsCustomsService asCustomsService;

    @Resource
    private AsSystemConfigService asSystemConfigService;

    @Resource
    private HatProvinceService hatProvinceService;

    @Resource
    private HatCityService hatCityService;

    @Resource
    private HatAreaService hatAreaService;

    @Resource
    private AsKeywordsService asKeywordsService;

    @Resource
    private AsAccountService asAccountService;

    @Resource
    private AsAccountDetailService asAccountDetailService;

    @Resource
    private AsUserService asUserService;

    @Resource
    private AsLogsService asLogsService;

    //前往代理商用户管理页面
    @RequestMapping(value = "/toAgentCustomManagePage")
    public String toAgentCustomManagePage( HttpSession session )
    {
        return "agentManage/agentCustomManage";
    }

    //显示当前用户的客户列表或输入客户名搜索条件后检索到的客户列表
    @RequestMapping(value = "/showAgentCustomManage" , produces = "application/json;charset=UTF-8")
    @ResponseBody
    @MethodLog( operateInfo = "查看代理商客户" )
    public String showAgentCustomManage(
            Integer page ,
            @RequestParam(value ="rows") Integer size ,
            String customName ,
            HttpSession session )
    {
        //System.out.println( "页码: " + page );
        //System.out.println( "页大小: " + size );
        //System.out.println( "搜索条件: " + customName );
        //获取当前用户
        AsUser user = (AsUser)session.getAttribute( "user" );
        //获取当前用户的客户数量
        Integer total = asCustomsService.returnCustomsCountByUserId( user.getId() );
        //System.out.println( "total: " + total );
        //获取当前页面显示的客户
        ArrayList<AsCustoms> customsList = asCustomsService.returnCustomsByUserIdAndName( user.getId() , customName , page , size );
        Pager<AsCustoms> pager = new Pager<>();
        pager.setTotal( total );
        pager.setRows( customsList );
        String jsonStr = JSON.toJSONStringWithDateFormat( pager , "yyyy-MM-dd hh:mm:ss" );
        //System.out.println(jsonStr);

        return jsonStr;
    }

    //前往添加客户界面
    @RequestMapping(value = "/toAddCustomPage")
    public String toAddCustomPage()
    {
        return "agentManage/addCustom";
    }

    @RequestMapping(value = "/comboboxJsonStr" , produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String comboboxJsonStr(
            String action , Integer provinceId , String customSearch ,
            Integer cityId , Integer userId , HttpSession session )
    {
        //System.out.println( "provinceId:  " + provinceId );
        //System.out.println( "cityId:  " + cityId );
        AsUser user = null;
        String jsonStr = "";
        switch ( action )
        {
            //返回企业类型选项
            case "customType":
                System.out.println( "customType" );
                jsonStr = asSystemConfigService.returnAvalibleTypeJsonStr( 5 );
                break;
            //返回证件类型选项
            case "cardType":
                System.out.println( "cardType" );
                jsonStr = asSystemConfigService.returnAvalibleTypeJsonStr( 6 );
                break;
            case "province":
                System.out.println( "province" );
                jsonStr = hatProvinceService.returnProvinceComboBoxJsonStr();
                break;
            case "city":
                System.out.println( "city" );
                jsonStr = hatCityService.returnCityComboBoxJsonStr( provinceId );
                break;
            case "area":
                System.out.println( "area" );
                jsonStr = hatAreaService.returnAreaComboBoxJsonStr( cityId );
                break;
                //返回当前账户余额
            case "money":
                user = (AsUser)session.getAttribute( "user" );
                jsonStr = asAccountService.getMoneyJsonStr( user.getId() );
                break;
                //返回服务类别
            case "productType":
                jsonStr = asSystemConfigService.returnAvalibleTypeJsonStr( 2 );
                break;
            //返回服务年限
            case "serviceYears":
                jsonStr = asSystemConfigService.getServiceYearsJsonStr();
                break;
            case "customs":
                user = (AsUser)session.getAttribute( "user" );
                jsonStr = asCustomsService.returnAvaliableCustomsByUserIdAndName( user.getId() , customSearch );
                break;
            case "appPrice":
                jsonStr = asSystemConfigService.getOpenAppPriceJsonStr();
                break;
                //返回用户存在的交易类型
            case "detailType":
                //userId为空查询当前用户,不为空查询指定用户
                user = (AsUser)session.getAttribute( "user" );
                if( userId == null )
                {
                    userId = user.getId();
                }
                jsonStr = asAccountDetailService.returnDetailTypeByUserId( userId );
                break;
            case "financialAccount":
                jsonStr = asAccountService.retunFinancialUserAccountJsonStr();
                break;
            case "usersAndRoleName":
                //返回财务管理页面搜索客户和角色名称
                jsonStr = asUserService.returnUsersAndRoleNameJsonStr();
                break;
            case "financialType":
                //返回可用的财务类型
                jsonStr = asSystemConfigService.returnAvalibleTypeJsonStr( 1 );
                break;
        }

        return jsonStr;
    }

    //前往修改客户界面
    @RequestMapping(value = "/toUpdateCustomPage")
    public String toUpdateCustomPage( Integer customId , Model model )
    {
        //System.out.println( "customId: " + customId );
        model.addAttribute( "customId" , customId );
        return "agentManage/updateCustom";
    }

    //前往查看客户界面
    @RequestMapping(value = "/toViewCustomPage")
    public String toViewCustomPage( Integer customId , Model model )
    {
        //System.out.println( "customId: " + customId );
        model.addAttribute( "customId" , customId );
        return "agentManage/viewCustom";
    }

    //代理商添加客户
    @RequestMapping(  value = "/addCustom" , produces = "application/json;charset=UTF-8")
    @ResponseBody
    @MethodLog( operateInfo = "" )
    public String addCustom( @Valid AsCustoms asCustoms , BindingResult result ,  HttpSession session , String dateTime )
    {
        String methodName = "addCustom";
        Class [] classes = new Class[]{ AsCustoms.class , BindingResult.class , HttpSession.class , String.class };
        //校验输入数据格式是否正确
        if( result.hasErrors() )
        {
            Map<String,String> errorMessage = new HashMap<>();
            for( FieldError error : result.getFieldErrors() )
            {
                //将错误消息放置于map中
                errorMessage.put( error.getField() , error.getDefaultMessage() );
            }
            AnnotationUtil.setOperateInfo( AgentManageController.class , methodName , "" , classes );
            //返回错误消息json格式字符串
            return JsonUtil.errorMessageJsonStr( errorMessage );
        }
        //校验无错误则添加客户
        AsUser user = (AsUser)session.getAttribute( "user" );
        //根据操作修改OperateInfo注解值
        String jsonStr = asCustomsService.addCustom( asCustoms , user , dateTime );
        AnnotationUtil.setOperateInfo( AgentManageController.class , methodName , "添加代理商客户" , classes );

        return jsonStr;
    }

    //代理商查询客户
    @RequestMapping( value = "/selectCustom" , produces = "application/json;charset=UTF-8")
    @ResponseBody
    @MethodLog( operateInfo = "查看代理商客户" )
    public String selectCustom( Integer customId )
    {
        String jsonStr = asCustomsService.returnOneCustomJsonStr( customId );

        return jsonStr;
    }

    //代理商更新客户
    @RequestMapping( value = "/updateCustom" , produces = "application/json;charset=UTF-8")
    @ResponseBody
    @MethodLog( operateInfo = "更新代理商客户" )
    public String updateCustom( AsCustoms custom )
    {
        String jsonStr = asCustomsService.updateCustom( custom );

        return jsonStr;
    }

    //代理商启用或停用客户
    @RequestMapping( value = "/enableOrDisableCustom" , produces = "application/json;charset=UTF-8")
    @ResponseBody
    @MethodLog( operateInfo = "" )
    public String enableOrDisableCustom( Integer customId , String action )
    {
        String methodName = "enableOrDisableCustom";
        Class [] classes = new Class[]{ Integer.class , String.class };
        String operateInfo = "";
        if( "startCustom".equals( action ) )
        {
            operateInfo = "启用代理商客户";
        }
        else if( "stopCustom".equals( action ) )
        {
            operateInfo = "停用代理商客户";
        }
        String jsonStr = asCustomsService.stopOrStartCustom( action , customId );
        AnnotationUtil.setOperateInfo( AgentManageController.class , methodName , operateInfo , classes );

        return jsonStr;
    }

    //根据id分别查询一组对应的省市区组合
    @RequestMapping( value = "/provinceCityArea" , produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getProvinceCityAreaJsonStr( Integer provinceId , Integer cityId , Integer areaId )
    {
        JSONObject json = new JSONObject();
        String province = hatProvinceService.returnProvinceNameById( provinceId );
        json.put( "province" , province);
        String city = hatCityService.returnCityNameById( cityId );
        json.put( "city" , city );
        String area = hatAreaService.returnAreaNameById( areaId );
        json.put( "area" , area );
        String jsonStr = json.toJSONString();
        System.out.println( jsonStr );

        return jsonStr;
    }

    //前往关键字申请管理页面
    @RequestMapping( value = "/toKeywordsApplicationManagePage" )
    public String toKeywordsApplicationManagePage()
    {
        return "agentManage/keywordsApplicationManage";
    }

    //显示当前用户的关键词申请管理页面
    @RequestMapping( value = "/showKeywordsDataGrid" , produces = "application/json;charset=UTF-8" )
    @ResponseBody
    @MethodLog( operateInfo = "查看已申请关键词" )
    public String showKeywordsApplicationManagePage(
            Integer page ,
            @RequestParam( value = "rows" ) Integer size ,
            String keywords ,
            HttpSession session )
    {
        //获取当前用户
        AsUser user = (AsUser)session.getAttribute( "user" );
        String jsonStr = asKeywordsService.returnKeywordsDataGridJsonStr( user.getId() , keywords , page , size );

        return jsonStr;
    }

    //前往关键字申请页面
    @RequestMapping( value = "/toKeywordsApplicationPage" )
    public String toKeywordsApplicationPage()
    {
        return "agentManage/keywordsApplication";
    }

    //关键词申请(开启事务)
    @RequestMapping( value = "/keywordsApplication" )
    @ResponseBody
    @MethodLog(operateInfo = "关键词申请" )
    public String keywordsApplication( AsKeywords keywords , HttpSession session , Integer detailType )
            throws Exception
    {
        //获取当前用户
        AsUser user = (AsUser)session.getAttribute( "user" );
        Integer resultCode = asKeywordsService.submitKeywordsApplication( keywords , user , detailType );

        return JsonUtil.successOrNotJsonStr( resultCode );
    }

    //关键词续费(开启事务)
    @RequestMapping( value = "/keyWordsCharge" )
    @ResponseBody
    @MethodLog(operateInfo = "关键词续费" )
    public String keyWordsCharge(
            AsKeywords keywords , HttpSession session ,
            Integer detailType , Double totalPrice )
    {
        //获取当前用户
        AsUser user = (AsUser)session.getAttribute( "user" );
        Integer resultCode = asKeywordsService.submitKeywordsRecharge( keywords , user , detailType , totalPrice );

        return JsonUtil.successOrNotJsonStr( resultCode );
    }

    //开通APP(开启事务)
    @RequestMapping( value = "/openApp" )
    @ResponseBody
    @MethodLog(operateInfo = "为关键词开通App" )
    public String openApp( Integer id , String appUserName , String appPassword ,
                           Double appPrice , HttpSession session , Integer detailType )
    {
        AsUser user = (AsUser)session.getAttribute( "user" );
        Integer resultCode = asKeywordsService.submitOpenApp( id , appUserName , appPassword , appPrice , detailType , user );
        return JsonUtil.successOrNotJsonStr( resultCode );
    }

    //前往代理商预付款页面
    @RequestMapping( value = "/toAgentPrePayManagePage" )
    public String toAgentPrePayManagePage()
    {
        return "agentManage/agentPrePayManage";
    }

    //显示代理商预付款页面
    @RequestMapping( value = "/showAgentPrePayManage"  , produces = "application/json;charset=UTF-8" )
    @ResponseBody
    @MethodLog( operateInfo = "查看代理商预付款" )
    public String showAgentPrePayManage(
            Integer page , @RequestParam( value = "rows") Integer size ,
            String start , String end , Integer detailType , HttpSession session )
    {
        AsUser user = (AsUser)session.getAttribute( "user" );
        String jsonStr = asAccountDetailService.returnAccountDetailOfPageJsonStr( user.getId() , page , size , start , end , detailType );

        return jsonStr;
    }

    //前往操作日志页面
    @RequestMapping(value = "/toLogsPage")
    public String toLogsPage()
    {
        return "agentManage/operateLogs";
    }

    //显示当前用户的所有操作日志
    @RequestMapping( value = "/showOperateLogsPage"  , produces = "application/json;charset=UTF-8" )
    @ResponseBody
    @MethodLog( operateInfo = "查看操作日志" )
    public String showOperateLogsPage(
            Integer page , @RequestParam( value = "rows") Integer size , HttpSession session )
    {
        //获取当前用户
        AsUser user = (AsUser)session.getAttribute( "user" );
        String jsonStr = asLogsService.returnLogsPageByUserId( user.getId() , null , page , size );

        return jsonStr;
    }
}
